package com.wxpay.controller;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.gson.Gson;
import com.honour.service.interfaced.UserInManager;
import com.system.controller.base.BaseController;
import com.system.property.WXProperty;
import com.system.redis.RedisDao;
import com.system.result.CodeMsg;
import com.system.result.Result;
import com.system.util.AppUtil;
import com.system.util.HttpClientUtil;
import com.system.util.PageData;
import com.system.util.Tools;

/**
 * 微信程序相关接口
 * @Function 
 * @Author zhaozhenhua
 * @Date 2018年5月31日
 */
@Controller
@RequestMapping(value="/wechat")
public class WeChatController extends BaseController{
	
	@Resource(name = "userinService")
	private UserInManager userinService;
	
	@Resource(name = "redisDaoImpl")
	private RedisDao redisDaoImpl;
	
	/**
	 * 微信小程序登陆凭证校验接口
	  * @Description
	  * @Author zhaozhenhua
	  * @date   2018年5月31日
	  * @param pd
	  * @return
	  * @throws Exception
	 */
	@RequestMapping(value="/login")
	@ResponseBody
	public Object login() {
		logBefore(logger, "微信小程序登陆凭证校验接口");
		PageData pd = new PageData();
		pd = this.getPageData();
		try {
			if (Tools.checkKey("WECHATLOGIN", pd.getString("FKEY"))) { // 检验请求key值是否合法
				if (AppUtil.checkParam("wechatlogin", pd)) { // 检查参数
			        //1.通过code获取access_token
			        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code";
			                      
			        url = url.replace("APPID",WXProperty.get("appid")).replace("SECRET",WXProperty.get("secret")).replace("CODE",pd.getString("js_code"));
			        String tokenInfoStr =  HttpClientUtil.httpGetRequest(url);
                    Gson gson = new Gson();
                    PageData tokenInfo = gson.fromJson(tokenInfoStr, PageData.class);
			        logger.info("tokenInfoObject:"+tokenInfo);
			        if(Tools.notEmpty(tokenInfo.getString("errcode"))){
			        	return Result.error_data(CodeMsg.CODE_INVALID, tokenInfo);
			        }
			        String openid = tokenInfo.getString("openid");  //用户唯一标识
                    String session_key = tokenInfo.getString("session_key");//会话密钥
                    String loginStatus = this.getSnowId();//自定义登陆态
                    redisDaoImpl.setex(loginStatus, 1800, openid+":"+session_key);
                    return Result.success(loginStatus);
				} else {
					return Result.error(CodeMsg.PARAM_LACK);
				}
			} else {
				return Result.error(CodeMsg.FKEY_FAIL);
			}
		} catch (Exception e) {
			logger.error(e.toString(), e);
			return Result.error(CodeMsg.SERVER_ERROR);
		} finally {
			logAfter(logger);
		}
	}
	
}
